<?php

namespace app\util;

/**
 * Class Tree
 * @package app\util
 */
class Tree
{
    /**
     * 生成无限分类
     *
     * @param array $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    public static function create($list = [], $pk = 'id', $pid = 'parent_id', $child = 'children', $root = 0)
    {
        $tree = [];
        if (is_array($list)) {

            //创建基于主键的数组引用
            $refer = [];
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }

            foreach ($list as $key => $data) {
                //判断是否存在parent
                $parentId = $data[$pid];

                if ($root == $parentId) {
                    $tree[] = &$list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = &$refer[$parentId];
                        $parent[$child][] = &$list[$key];
                    }
                }
            }
        }

        return $tree;
    }
}